from datetime import datetime
import json
from django.views.decorators.http import require_POST, require_GET
from django.views.decorators.csrf import csrf_exempt
from tanxi.client.Handler.JsonResponse import create_response
from tanxi.client.Handler.Logger import log_error, log_info
from django.conf import settings

# 数据库选择
if settings.DATABASE_TYPE == 'mysql':
    from tanxi.client.utils.mysql.AIProjects_mysql import AIProjectUpdateHandler, AIProjectQueryHandler
elif settings.DATABASE_TYPE == 'sqlite':
    # from tanxi.client.utils.sqlite.ai_projects_sqlite import AIProjectUpdateHandler, AIProjectQueryHandler 
    pass
else:
    raise ValueError("Unsupported database type specified in settings.")

# 初始化处理器
ai_query = AIProjectQueryHandler()
ai_update = AIProjectUpdateHandler()

@require_GET
@csrf_exempt
def get_ai_projects(request):
    """获取AI项目列表"""
    try:
        project_id = request.GET.get('id')
        name = request.GET.get('name')
        project_type = request.GET.get('type')
        author = request.GET.get('author')
        is_public = request.GET.get('is_public')

        if project_id or name or project_type or author or is_public:
            projects = ai_query.query_ai_projects(
                id=project_id,
                name=name,
                type=project_type,
                author=author,
                is_public=is_public
            )
            projects = list(projects)
            log_info(f"按参数查询AI项目结果: {projects}")
        else:
            projects = ai_query.query_ai_projects()
            projects = list(projects)
            log_info(f"查询所有AI项目结果: {projects}")
        
        return create_response(code=200, message="Success", remarks="查询成功", data=projects)
    except Exception as e:
        log_error(f"查询AI项目出错: {str(e)}")
        return create_response(code=500, message="Error", remarks="查询失败", data=None)

@require_POST
@csrf_exempt
def write_ai_project(request):
    """创建或更新AI项目"""
    try:
        data = json.loads(request.body)
        log_info(f"接收到的AI项目数据: {data}")

        # 处理必填字段和默认值
        project_data = {
            'name': data.get('name', ''),
            'description': data.get('description', ''),
            'type': data.get('type', 'other'),
            'author': data.get('author', ''),
            'demo_url': data.get('demo_url', ''),
            'repo_url': data.get('repo_url', ''),
            'status': data.get('status', 'active'),
            'tech_stack': data.get('tech_stack', []),
            'is_public': data.get('is_public', True),
            'user_id': data.get('user_id')
        }

        # 处理封面图片
        if 'cover_image' in data:
            project_data['cover_image'] = data['cover_image']

        # 处理ID
        if 'id' in data and data['id']:
            project_data['id'] = data['id']

        # 调用处理器
        result = ai_update.update_or_create_ai_project(project_data)
        return create_response(code=200, message="Success", remarks="操作成功", data=result)

    except json.JSONDecodeError:
        return create_response(code=400, message="Error", remarks="请求体不是有效的JSON格式", data=None)
    except ValueError as e:
        return create_response(code=400, message="Error", remarks=str(e), data=None)
    except Exception as e:
        log_error(f"操作AI项目出错: {str(e)}")
        return create_response(code=500, message="Error", remarks="服务器内部错误", data=None)

@require_POST
@csrf_exempt
def delete_ai_project(request):
    """删除AI项目"""
    try:
        data = json.loads(request.body)
        project_id = data.get('project_id')
        if not project_id:
            return create_response(code=400, message="Error", remarks="缺少project_id参数", data=None)
        
        success = ai_update.delete_ai_project(project_id)
        if success:
            return create_response(code=200, message="Success", remarks="删除成功", data=None)
        else:
            return create_response(code=404, message="Error", remarks="AI项目不存在", data=None)
    except Exception as e:
        log_error(f"删除AI项目出错: {str(e)}")
        return create_response(code=500, message="Error", remarks="服务器内部错误", data=None)